package com.zwr.myproject2

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.FragmentTransaction
import android.widget.RadioGroup
import com.zwr.myproject2.ui.fragment.OneFragment
import com.zwr.myproject2.ui.fragment.TwoFragment
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() , RadioGroup.OnCheckedChangeListener{


    private val oneFragment: OneFragment =  OneFragment()
    private var twoFragment: TwoFragment? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        init()
        initDefultView()
    }

    /**
     * 初始化
     */
    private fun init() {
        rg.setOnCheckedChangeListener(this)
    }

    /**
     * 显示默认的fragment
     */
    private fun initDefultView() {
        val fm = supportFragmentManager
        val ft = fm.beginTransaction()
        ft.add(R.id.fl_content, oneFragment)
        ft.commit()
    }


    /**
     * RadioGroup监听
     */
    override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {

        val fm =  supportFragmentManager
        val ft = fm.beginTransaction()

        //先隐藏全部的fragment，再选择要显示的fragment
        hidtFragment(ft)

        when(checkedId){
            R.id.rb1 ->  ft.show(oneFragment)
            R.id.rb2->{
                if(null==twoFragment){
                    twoFragment = TwoFragment()
                    ft.add(R.id.fl_content, twoFragment!!)
                }else{
                    ft.show(twoFragment!!)
                }
            }
        }

        ft.commit()
    }

    /**
     * 隐藏fragment
     */
    private fun hidtFragment(ft: FragmentTransaction) {
        ft.hide(oneFragment)

        if (twoFragment!=null){
            ft.hide(twoFragment!!)
        }
    }
}
